package com.example.bes952.springboot2.bcs.controller;

import com.example.bes952.springboot2.bcs.modle.Book;
import com.example.bes952.springboot2.bcs.producer.CycleGeneratorStreamMessageRunner;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.ObjectRecord;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/bcs")
@CrossOrigin
public class TestController {

    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CycleGeneratorStreamMessageRunner cycleGeneratorStreamMessageRunner;

    @GetMapping(value = "/add/{key}/{value}")
    public void addKey(@PathVariable(value = "key") String key, @PathVariable(value = "value") String value) {
        redisTemplate.opsForValue().set(key, value);
    }

    @GetMapping(value = "/get/{key}")
    public String getKey(@PathVariable(value = "key") String key) {
        return String.valueOf(redisTemplate.opsForValue().get(key));
    }

    @GetMapping(value = "/del/{key}")
    public boolean deleteKey(@PathVariable(value = "key") String key) {
        return redisTemplate.delete(key);
    }

    @GetMapping(value = "/stream")
    public void streamSend() {
        Book book = new Book();
        book.setTitle("bcs");
        book.setAuthor("bes");
        log.info("product a message: [{}]", book);
        ObjectRecord<String, Book> record = StreamRecords.newRecord().in("stream-001")
                .ofObject(book)
                .withId(RecordId.autoGenerate());
        RecordId recordId = redisTemplate.opsForStream().add(record);
        log.info("record-id:[{}]", recordId);
    }

}
